//
//  SettingViewController.m
//  Recipe
//
//  Created by bing han on 12-7-3.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SettingViewController.h"
#import "BaseUrl.h"
#import "ASIHTTPRequest.h"
#import "User.h"
#import "JSONKit.h"
#import "DBOptions.h"
#import "FMDatabase.h"
#import "DisherViewController.h"
#import "Unit.h"
#import "AppDelegate.h"
#import "DisherType.h"
#import "DisherArray.h"

@interface SettingViewController ()

@end

@implementation SettingViewController
@synthesize uid = _uid;
@synthesize delegate;

@synthesize updMenuBtn = _updMenuBtn, updTypeBtn = _updTypeBtn, updMenuActi = _updMenuActi, updTypeActi = _updTypeActi,backBtn = _backBtn;
//@synthesize percentPrgV = _percentPrgV;
//@synthesize progressindex, progresscount;
//@synthesize timer = _timer;


//-(void) setprogressB{
//    NSLog(@"%f / %f ",self.progressindex,self.progresscount);
//    if (self.progressindex/self.progresscount == 1) {
//        [timer invalidate];
//        [_percentPrgV setHidden:YES];
//    }else {
//        [_percentPrgV setHidden:NO];
//        [_percentPrgV setProgress:(self.progressindex/self.progresscount)];
//    }
//}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    _uid = [[User newInstance] uid];
    
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:YES];
//    [_percentPrgV setHidden:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

#pragma mark button click
//更新分类
-(IBAction)updateType:(id)sender{
    [self disableBtn];
//    self.progressindex = 0;
//    timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(setprogressB) userInfo: nil repeats: YES];
//    
    [_updTypeActi setHidden:NO];
    [_updTypeActi startAnimating];
    NSString *urlStr = [[NSString alloc] initWithString:UPDATETYPE];
    urlStr = [urlStr stringByAppendingString:@"&username="];
    urlStr = [urlStr stringByAppendingString:_uid];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    
    NSError *error = [request error];
    if (!error) {
        NSString *response = [request responseString];
        NSDictionary *root = [response objectFromJSONString];
        
        if ([[root objectForKey:@"result"] isEqualToString:@"1"]) {
            NSArray *types = [root objectForKey:@"types"];
            DBOptions *dbOption = [DBOptions newInstence];
            FMDatabase *fmdb = dbOption.fmdatabase;
//            self.progresscount = [types count];
            for (NSDictionary *type in types) {
//                self.progressindex += 1;
                [fmdb executeUpdate:@"insert into type(key,parentkey,typecn,typeen)values(?,?,?,?);",[type objectForKey:@"key"],[type objectForKey:@"parentkey"],[type objectForKey:@"type"],[type objectForKey:@"type"]];
            }
            [dbOption closeDatabase];
        }
    }
    [_updTypeActi stopAnimating];
    NSArray *param = [[NSArray alloc] initWithObjects:@"提示",@"更新菜品分类完成。",@"确定", nil];
    DisherType *dt = [DisherType newInstence];
    [dt initDisherType];
    [delegate initType];
    [self showMsg:param];
    [self enableBtn];
    
}
//更新菜单
-(IBAction)updateMenu:(id)sender{
    [self disableBtn];
//    self.progressindex = 0;
//    timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(setprogressB) userInfo: nil repeats: YES];
    
    [_updMenuActi setHidden:NO];
    [_updMenuActi startAnimating];
    NSString *urlStr = [[NSString alloc] initWithString:UPDATEMENU];
    urlStr = [urlStr stringByAppendingString:@"&username="];
    urlStr = [urlStr stringByAppendingString:_uid];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    
    NSError *error = [request error];
    if (!error) {
        NSString *response = [request responseString];
        NSDictionary *root = [response mutableObjectFromJSONString];
        
        if ([[root objectForKey:@"result"] isEqualToString:@"1"]) {
            NSArray *types = [root objectForKey:@"contents"];
            DBOptions *dbOption = [DBOptions newInstence];
            FMDatabase *fmdb = dbOption.fmdatabase;
//            self.progresscount = [types count];
            for (NSDictionary *type in types) {
//                self.progressindex += 1;

                NSString *smallfile = [self saveFile:[type objectForKey:@"key"] type:@"small" url:[type objectForKey:@"csmallurl"]];
                [type setValue:smallfile forKey:@"csmallurl"];
//                [smallfile release];
                
                NSString *bigfile = [self saveFile:[type objectForKey:@"key"] type:@"big" url:[type objectForKey:@"cbigurl"]];  
                [type setValue:bigfile forKey:@"cbigurl"];
//                [bigfile release];
                NSString *tmpprice = [type objectForKey:@"cprice"];
                tmpprice = [tmpprice substringToIndex:[tmpprice length] -1];
                [fmdb executeUpdate:@"insert into dishes(businesskey,type,cnamecn,cnameen,csmallurl,cbigurl,cprice,remarks)values(?,?,?,?,?,?,?,?);",[type objectForKey:@"key"],[type objectForKey:@"type"],[type objectForKey:@"cname"],[type objectForKey:@"cname"],[type objectForKey:@"csmallurl"],[type objectForKey:@"cbigurl"],tmpprice,[type objectForKey:@"remarks"]];
//                [type release];
            }
            
            [dbOption closeDatabase];
        }
    }
    DisherArray *da = [DisherArray newInstence];
    [da initDisherArray];
    [_updMenuActi stopAnimating];
    NSArray *param = [[NSArray alloc] initWithObjects:@"提示",@"更新菜品信息完成。",@"确定", nil];
    [delegate initMenu];
    [self showMsg:param];
    [self enableBtn];
}

-(NSString *)saveFile:(NSString *) businesskey type:(NSString *) imgtype url:(NSString *) imgurl{

    NSString *filename = [businesskey stringByAppendingString:imgtype];
    NSURL *fileurl = [NSURL URLWithString:imgurl];
    NSString *filepath = [DISHERIMAGEPATH stringByAppendingString:filename];
    NSData *imgdata=nil;
    BOOL isFileExist=[[NSFileManager defaultManager] fileExistsAtPath:filepath];
    if (!isFileExist) {
        imgdata = [NSData dataWithContentsOfURL:fileurl];
        [imgdata writeToFile:filepath atomically:NO];
    }
    return filename;
}

-(void) enableBtn{
    _updMenuBtn.enabled = YES;
    _updTypeBtn.enabled = YES;
    _backBtn.enabled = YES;
}

-(void) disableBtn{
    _updMenuBtn.enabled = NO;
    _updTypeBtn.enabled = NO;
    _backBtn.enabled = NO;
}

-(void) showMsg:(NSArray *) param{
    
    UIAlertView *showMsg = [[UIAlertView alloc] initWithTitle:[param objectAtIndex:0]  message:[param objectAtIndex:1] delegate:self cancelButtonTitle:[param objectAtIndex:2] otherButtonTitles:nil];
    [showMsg show];
    //    [showMsg release];
}
//返回
-(IBAction)doBack:(id)sender{

    [delegate dissmissview];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [_uid release];
    _updMenuBtn = nil;
    _updTypeBtn = nil;
    _backBtn = nil;
    _updMenuActi = nil;
    _updTypeActi = nil;
//    _percentPrgV = nil;
//    _timer = nil;
    // Release any retained subviews of the main view.
    
}
@end
